/**第114题*/
//给定一个二叉树，原地将它展开为一个单链表。 
//
// 
//
// 例如，给定二叉树 
//
//     1
//   / \
//  2   5
// / \   \
//3   4   6 
//
// 将其展开为： 
//
// 1
// \
//  2
//   \
//    3
//     \
//      4
//       \
//        5
//         \
//          6 
// Related Topics 树 深度优先搜索 
// 👍 680 👎 0

package tree.leetcode.editor.cn;

import com.dq.tree.Tree;
import com.dq.tree.TreeNode;

import java.util.ArrayList;
import java.util.List;

public class FlattenBinaryTreeToLinkedList {
    public static void main(String[] args) {
        Solution solution = new FlattenBinaryTreeToLinkedList().new Solution();
        Integer[] a = new Integer[]{1,2,5,3,4,null,6};
        TreeNode root = Tree.proATree(a);
        solution.flatten(root);
        show(root);

    }
    public static void show(TreeNode node){
        List<String> res = new ArrayList<>();
        res.add(node.val+"");
        node = node.right;

        while(node!=null){
            res.add(node.val+"");
            node = node.right;
        }
        System.out.println(res);
    }
        //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        if(root==null) return;
        /**** 后序遍历位置 ****/
        // 1、左右子树已经被拉平成一条链表
        flatten(root.left);
        flatten(root.right);

        TreeNode right = root.right;

        if (root.left!=null){
            // 2、将左子树作为右子树
            root.right = root.left;
            // 3、将原先的右子树接到当前右子树的末端
            TreeNode temp = root.left;
            while(temp.right!=null) temp = temp.right;
            temp.right = right;
            root.left = null;
        }

    }
}
//leetcode submit region end(Prohibit modification and deletion)

}